import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from '../api/request';

// 定义请求参数类型
interface MedicalContentParams {
  page?: number;          // 页码
  pageSize?: number;      // 每页显示条数
  contentType: 'healthNews' | 'topicCheck' | 'mixedNews'; // 内容类型
  channel_id?: string;    // 频道ID（可选）
  from_wx_mini?: string;  // 来源参数
  partner?: string;       // 合作方参数
  release_time?: string;  // 发布时间范围
}
// 定义返回数据类型
interface MedicalContentItem {
  id: number;
  title: string;
  image: string;
  date_str: string;
  view_times: number;
  channel_id: number;
  channel_name: string;
  [key: string]: any; // 其他可能的字段
}

interface TopicCheckItem {
  id: number | string;
  // 专家名称（有些在顶层 name）
  name?: string;
  // 列表标题（问题/主题标题）
  title?: string;
  image?: string;
  doctor_info?: {
    doctor_name?: string;
    hospital_name?: string;
    title?: string; // 职称
    image?: string; // 头像
    avatar?: string;
    [key: string]: any;
  };
  topic_info?: {
    title?: string;
    digest?: string;
    created_time?: string; // 例如 “10月11日”
    cover_image?: string;
    [key: string]: any;
  };
  [key: string]: any; // 其他可能的字段
}


// 创建异步Thunk
export const fetchMedicalContent = createAsyncThunk(
  'medicalContent/fetchMedicalContent',
  async (params: MedicalContentParams) => {
    // 根据内容类型选择不同的API端点
    const url = params.contentType === 'healthNews' || params.contentType === 'mixedNews'
      ? '/cooperation/wap/health_news/'
      : '/cooperation/wap/topic_check_list/';

    const res = await axios.get<{
      content_list?: MedicalContentItem[];
      topic_check_list?: TopicCheckItem[];
      count?: number;
      has_more_page?: boolean;
      page_info?: any;
      banner_list?: any[];
    }>(url, {
      params: {
        page: params.page || 1,
        pageSize: params.pageSize || 10,
        from_wx_mini: params.from_wx_mini || 'true',
        partner: params.partner || 'chunyuyisheng',
        release_time: params.release_time || '30',
        ...(params.channel_id && { channel_id: params.channel_id }),
      },
    });

    // 统一数据格式，与artSlice保持一致
    return {
      artList: params.contentType === 'healthNews' || params.contentType === 'mixedNews'
        ? res.data.content_list || []
        : res.data.topic_check_list || [],
      total: res.data.count || res.data.topic_check_list?.length || 0,
      page: params.page || 1,
      pageSize: params.pageSize || 10,
      hasMore: res.data.has_more_page || res.data.page_info?.has_more_page || false,
      contentType: params.contentType,
      bannerList: res.data.banner_list || []
    };
  }
);

// 初始状态
const initialState = {
  artList: [] as (MedicalContentItem | TopicCheckItem)[],
  total: 0,
  page: 1,
  pageSize: 10,
  isLoading: false,
  hasMore: true,
  currentType: null as 'healthNews' | 'topicCheck' | 'mixedNews' | null,
  bannerList: [] as any[],
  // 额外增加：按类型缓存列表，避免多个频道互相覆盖
  byType: {
    healthNews: [] as MedicalContentItem[],
    topicCheck: [] as TopicCheckItem[],
    mixedNews: [] as (MedicalContentItem | TopicCheckItem)[],
  }
};

// 创建切片
const medicalContentSlice = createSlice({
  name: 'medicalContent',
  initialState,
  reducers: {
    // 重置内容列表
    resetContent: (state) => {
      state.artList = [];
      state.page = 1;
      state.total = 0;
      state.hasMore = true;
    },
    // 清空特定类型的内容
    clearContent: (state, action) => {
      state.artList = [];
      state.page = 1;
      state.total = 0;
      state.hasMore = true;
      state.currentType = action.payload;
    }
  },
  extraReducers: (builder) => {
    builder
      // 处理请求 pending 状态
      .addCase(fetchMedicalContent.pending, (state) => {
        state.isLoading = true;
      })
      // 处理请求 fulfilled 状态
      .addCase(fetchMedicalContent.fulfilled, (state, { payload }) => {
        state.isLoading = false;
        state.currentType = payload.contentType;
        state.bannerList = payload.bannerList;
        
        // 第一页替换数据，后续页追加数据
        if (payload.page === 1) {
          state.artList = payload.artList;
        } else {
          state.artList = [...state.artList, ...payload.artList];
        }
        // 同步写入按类型缓存，防止不同频道互相覆盖
        if (payload.contentType === 'healthNews') {
          state.byType.healthNews = payload.page === 1
            ? (payload.artList as MedicalContentItem[])
            : ([...state.byType.healthNews, ...(payload.artList as MedicalContentItem[])]);
        } else if (payload.contentType === 'topicCheck') {
          state.byType.topicCheck = payload.page === 1
            ? (payload.artList as TopicCheckItem[])
            : ([...state.byType.topicCheck, ...(payload.artList as TopicCheckItem[])]);
        } else if (payload.contentType === 'mixedNews') {
          state.byType.mixedNews = payload.page === 1
            ? payload.artList
            : ([...state.byType.mixedNews, ...payload.artList]);
        }
        
        state.total = payload.total;
        state.page = payload.page;
        state.pageSize = payload.pageSize;
        state.hasMore = payload.hasMore;
      })
      // 处理请求 rejected 状态
      .addCase(fetchMedicalContent.rejected, (state) => {
        state.isLoading = false;
      });
  }
});

// 导出 actions
export const { resetContent, clearContent } = medicalContentSlice.actions;

// 导出 reducer
export default medicalContentSlice.reducer;
